﻿using System;
using System.Collections.Generic;

namespace TestUp.Models.TestWorkers.TestsModel
{
    public class FillTest : TestQuestion
    {
        private static readonly string StartingPlaceholder = "##_";
        private static readonly string EndingPlaceholder = "_##";

        public string Text { get; set; }
        public Dictionary<int, string> Statements { get; set; }

        public FillTest()
        {
            TestType = TestTypes.FillTest;
        }

        public bool Check(List<int> fillAnswers)
        {
            var correctList = ParseCorrectAnswers(Text);
            if (fillAnswers.Count != correctList.Count)
                return false;

            for (int i = 0; i < correctList.Count; i++)
                if (correctList[i] != fillAnswers[i])
                    return false;

            return true;
        }

        private List<int> ParseCorrectAnswers(string text)
        {
            List<int> resultList = new List<int>();

            int currentPos = 0;
            int startPosition = text.IndexOf(StartingPlaceholder, currentPos, StringComparison.Ordinal);

            while (startPosition >= 0)
            {
                currentPos = startPosition + StartingPlaceholder.Length;
                int endPosition = text.IndexOf(EndingPlaceholder, currentPos, StringComparison.Ordinal);

                var strId = text.Substring(currentPos, endPosition - currentPos);

                int id;
                if (Int32.TryParse(strId, out id))
                    resultList.Add(id);

                startPosition = text.IndexOf(StartingPlaceholder, currentPos + StartingPlaceholder.Length, StringComparison.Ordinal);
            }

            return resultList;
        }
    }
}